<template>
  <div style="width: 100%;display: flex;flex-direction: column">

    <el-button v-if="config.showSelectAll != false" type="primary" style="align-self: end" @click="selectAll">{{chooseAll ? '反选':'全选'}}</el-button>
    <ElTree
        style="max-width: 600px"
        :data="dataList"
        :show-checkbox="config.showCheckBox != false"
        ref="treeRef"
        @check="onChange"
        @node-click="nodeClick"
        :default-expand-all="config.defaultExpandAll"
        :default-checked-keys="defaultCheckedKeys"
        :node-key="defaultProps.value"
        :props="defaultProps"
    />
  </div>

</template>
<script lang="ts" setup>
import treeUtil from "/@/utils/treeUtil.ts";

const props = defineProps({
  modelValue: {

  },
  placeholder: {},
  config: {
    type: Object,
    default: () => ({
      placeholder: '请选择',
      modelValue: null,
      fullWidth: false,
      showAllLevels: true,
      showSelectAll: true,
      clearable: true,
      url: null,
      defaultExpandAll: false,
      isTree:false,
      props: {
        label: 'label',
        value: 'value',
        children: 'children',
        emitPath: false,
        checkStrictly: false,
        multiple: false
      }

    }),
  },
})
const emits = defineEmits(['update:modelValue', 'initData'])
const treeRef = ref(null)
const chooseAll = ref(false)
const dataList = ref([]);
const defaultCheckedKeys = ref([] as any)
const getData = async () => {
  const options = await props.config['optionsFunction']();
  if (options.props) {
    let tree = treeUtil.handleTree(options,options.props);
    dataList.value = tree
  } else {
    dataList.value =  options;
  }
};
const nodeClick =(node)=> {
  if (props.config.click) {
    props.config.click(node)
  }
}
// 共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
const onChange = (value,check,childCheck) => {
  var checked1 = treeRef.value.getCheckedNodes(false)
  var checked2 = treeRef.value.getHalfCheckedNodes()
  let checked = [].concat(checked1,checked2).map(value=>value[defaultProps.value]).join(',')
  emits('update:modelValue', checked);
};
const selectAll=()=> {
  chooseAll.value = !chooseAll.value
  const keys = dataList.value.map(item => item[defaultProps.value]);
  if (chooseAll.value) {
    treeRef.value.setCheckedKeys(keys);
  } else {
    treeRef.value.setCheckedKeys([]);
  }
}
// /** 监听 modelValue 的变化 */
watch(
  () => props.modelValue,  // 监听传入的 modelValue
  async (newValue) => {
    if (!dataList.value || dataList.value.length == 0) {
      await getData();
    }
    if (newValue) {
      if (treeRef.value) {
        let leaf = []
        treeUtil.findLeafNodes(dataList.value,leaf);
        let allIds = !newValue ? []:  newValue.split(',').map(value=>parseInt(value));
        console.log(allIds);
        let value1 = allIds.filter(value=> leaf.filter(v=>v == value).length == 0);
        console.log(value1);
        defaultCheckedKeys.value = value1
      }
    }
  },{immediate: true}
);
let defaultProp = {
  label: 'label',
  value: 'value',
  children: 'children',
  emitPath: false,
  checkStrictly: false,
  multiple: false,
}
const defaultProps = Object.assign(defaultProp, props.config.props);


</script>
